package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.DIYException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.CostantVod;
import com.atguigu.vod.utils.InitObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class UploadController {

    @Autowired
    private VodService vodService;

    //上传视频方法
    @PostMapping("uploadAlyunVideo")
    public R uploadAlyiVideo(MultipartFile file){
        String videoId=vodService.uploadVideoAly(file);

        return R.ok().data("videoId",videoId);
    }

    //根据视频Id删除阿里云视频
    @DeleteMapping("removeAlyVideo/{id}")
    public R removeAlyVideo(@PathVariable String id){
        try {
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient(CostantVod.ACCESS_KEY_ID, CostantVod.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request=new DeleteVideoRequest();
            //向request设置id
            request.setVideoIds(id);
            client.getAcsResponse(request);
            return R.ok();
        }catch (Exception e){
            throw  new DIYException(20001,"删除视频失败");
        }
    }
    //删除多个阿里云视频
    //参数是多个视频id
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeMoreAlyVideo(videoIdList);

        return R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        try{
            System.out.println("进入getPlayAuth方法");
            //创建初始化对象
         DefaultAcsClient client=InitObject.initVodClient(CostantVod.ACCESS_KEY_ID,CostantVod.ACCESS_KEY_SECRET);
         //创建获取凭证request response
            GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
            //向request里设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            System.out.println(playAuth);
            return R.ok().data("playAuth",playAuth);

        }catch (Exception e){
            throw new DIYException(20001,"凭证获取失败");
        }
    }
}
